import Vue from 'vue'
import { Message } from 'element-ui'
import { getUserInfo } from './permission.js'

// 自定义指令
const hasRole = Vue.directive('hasRole', {
	bind: function(el, binding, vnode) {
		// 监听按钮点击事件
		el.addEventListener('click', function(){
			let userInfo = JSON.parse(getUserInfo());
			let rolesList = binding.value;
			// 判断是否具有操作权限
			if ( !rolesList.includes(userInfo.role) ) {
				let options = {
					message: '很抱歉，您的操作权限不足！',
					type: 'error',
					duration: 800
				}
				Message(options);
			}
		})
	},
	inserted: function(el, binding, vnode) {
		let userInfo = JSON.parse(getUserInfo());
		let rolesList = binding.value;
		// 判断是否拥有角色权限
		if ( !rolesList.includes(userInfo.role) ) {
			// 隐藏按钮
			el.style['display'] = 'none';
		}
	},
	update: function(el, binding, vnode) {
		let userInfo = JSON.parse(getUserInfo());
		let rolesList = binding.value;
		// 角色状态切换时，需重新判断
		if ( !rolesList.includes(userInfo.role) ) {
			//el.parentNode.removeChild(el);
			el.style['display'] = 'none';
		} else {
			el.style['display'] = 'inline-block';
		}
	}
})

export default hasRole